package com.alogic.validator.impl;

import com.alogic.matcher.CommonMatcher;
import com.alogic.matcher.MatcherFactory;
import com.alogic.validator.Validator;
import com.anysoft.util.BaseException;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

/**
 * CommonMatcher
 *
 * @since 1.6.13.17 [20200923 duanyy] <br>
 *
 * @version 1.6.13.25 [20201110 duanyy] <br>
 * - 修复validator的问题
 */
public class Matcher extends Validator.Abstract{
    protected boolean exclude = false;
    protected CommonMatcher matcher = null;
    @Override
    public void configure(Properties p) {
        super.configure(p);
        exclude = PropertiesConstants.getBoolean(p,"exclude",exclude,true);
        String pattern = PropertiesConstants.getString(p, "pattern", "(wildcard)*", true);
        if (StringUtils.isNotEmpty(pattern)) {
            try {
                matcher = MatcherFactory.getMatcher(pattern, p);
            } catch (Exception ex) {
                LOG.error("Can not create matcher:" + pattern);
            }
        }
    }

    @Override
    public boolean check(String value, Properties ctx,boolean throwException) {
        boolean result = true;
        if (matcher != null){
            result = exclude?!matcher.isMatch(value):matcher.isMatch(value);
        }
        if (!result && throwException){
            throw new BaseException(getCode(ctx),getMessage(ctx));
        }
        return result;
    }

    @Override
    public boolean check(String value, Properties ctx, Listener listener) {
        boolean result = check(value,ctx,false);

        if (listener != null){
            listener.result(result,value,this,ctx);
        }

        return result;
    }
}